Ext.define('BISC.view.FilterManagerAttributesInput', {
    extend: 'Ext.form.Panel',
    alias: ['widget.filtermanagerattributesinput'],
    id: 'formAddFilterAttribute',
    title: 'Attributes',
    bodyPadding: 10,
    border: false,
    initComponent: function() {
        var me = this;

        Ext.applyIf(me, {
            items: [
                {
                    xtype: 'panel',
                    border: false,
                    id: 'filterAttributesPanel',
                    data: me.mainForm.filter.attributes,
                    tpl: new Ext.XTemplate('<table><tr><th></th><th class="thStyle">A/Dissociate</th><th class="thStyle">Overwrite?</th><th class="thStyle">Attribute</th></tr><tpl for=".">' +
                                '<tr>' +
                                    '<td><button class="removeAttributeBtn" attribute-id="{id}">Remove</button></td>' +
                                    '<td><button class="toggleAdditiveBtn" attribute-id="{id}" style="color:{[this.getColor(values.isAdd)]};">{[this.getText(values.isAdd)]}</button></td>' +
                                    '<td><input class="overrideCbx" {[this.isChecked(values.isOverride)]} attribute-id="{id}" type="checkbox"></td>' +
                                    '<td>{[this.printMainText(values)]}</td>' +
                                '</tr>' +
                            '</tpl></table>', {
                                isChecked: function( isOverride ) {
                                    if ( isOverride ) return 'checked="checked"';
                                    return '';
                                },
                                getColor: function( isAdd ) {
                                    if ( isAdd ) return 'green';
                                    return 'red';
                                },
                                getText: function( isAdd ) {
                                    if ( isAdd ) return '+';
                                    return '-';
                                },
                                printMainText: function( values ) {
                                    var string = values.value;
                                    if ( values.fields.length > 0 ) {

                                        if ( typeof values.format == 'undefined' ) {
                                            // path
                                            if ( values.value.charAt( values.value.length-1 ) != '/' ) string += '/';
                                            Ext.each( values.fields, function( field ) {
                                                string += '<span style="font-weight:bold">' + field.text + '</span>/';
                                            });
                                            string += 'image.ext';
                                        } else {
                                            // filename
                                            var formatString = '';
                                            switch ( values.format ) {
                                                case 'upper':
                                                    formatString = 'uppercase';
                                                    break;
                                                case 'lower':
                                                    formatString = 'lowercase';
                                                    break;
                                                case 'ucfirst':
                                                    formatString = 'first character uppercase only';
                                                    break;
                                            }
                                            string = '<span style="font-weight:bold">image.ext</span> > <span style="font-weight:bold">' + values.value + '</span> > ' + '<span style="font-weight:bold">' + values.fields[0].text + '</span> as ' + formatString + '.';
                                        }
                                    } else {
                                        // single
                                        string = values.category.title + ': <span style="font-weight:bold">' + string + '</span>';
                                    }
                                    return string;
                                }
                            }
                    ),
                    scope: me,
                    listeners: {
                        afterrender: function() {
                            me.addDataviewItemListeners();
                        }
                    }
                },
                {
                    xtype: 'combo',
                    fieldLabel: 'Add attribution',
                    queryMode: 'local',
                    displayField: 'value',
                    valueField: 'key',
                    store: Ext.create('Ext.data.Store', {
                        fields: ['key', 'value'],
                        data: [
                            {key: 'single', value: 'Single Attribute'},
                            {key: 'path', value: 'Path Interpolated'},
                            {key: 'filename', value: 'Filename Interpolated'}
                        ]
                    }),
                    listeners: {
                        change: function( combo, newVal, oldVal, opts ) {
                            var oldF = Ext.getCmp('addAttr'+oldVal);
                            var newF = Ext.getCmp('addAttr'+newVal);
                            if ( oldF ) oldF.hide();
                            if ( newF ) newF.show();
                        }
                    }
                },
                {
                    xtype: 'component',
                    html: '<div id="addAttrError" style="color: red; padding: 5px; font-weight: bold;"></div>'
                },
                {
                    xtype: 'panel',
                    border: false,
                    hidden: true,
                    id: 'addAttrsingle',
                    items: [
                        {
                            xtype: 'combo',
                            id: 'attributeSearchCombo',
                            emptyText: 'Type to search attributes.',
                            store: 'AttributesStore',
                            displayField: 'title',
                            queryParam: 'filter',
                            typeAhead: false,
                            minChars: 2,
                            hideLabel: true,
                            hideTrigger: true,
                            anchor: '100%',
                            width: 500,
                            listConfig: {
                                loadingText: 'Looking for attributes...',
                                emptyText: 'No matching attributes found.',
                                getInnerTpl: function() {
                                        return '<div class="attributeSearchItem">'+
                                                '<h3><span style="font-weight:bold">{categoryTitle}</span>: {title}</h3>'+
                                        '</div>';
                                }
                            },
                            pageSize: 10,
                            listeners: {
                                scope: this,
                                select: function(combo, selection) {
                                    var val = selection[0];
                                    if ( val ) {
                                        var tempAttribute = {
                                            id: me.mainForm.filter.tempId++,
                                            type: 'static',
                                            isAdd: true,
                                            isOverride: false,
                                            attributeId: val.get('attributeId'),
                                            category: {
                                                categoryId: val.get('categoryId'),
                                                bisId: val.get('bisId'),
                                                title: val.get('categoryTitle')
                                            },
                                            value: val.get('title'),
                                            fields: []
                                        };
                                        if ( me.attributeExists( tempAttribute ) ) {
                                            Ext.get('addAttrError').update('Attribute already exists.');
                                        } else {
                                            if ( tempAttribute.value != '' ) {
                                                me.mainForm.filter.attributes.push( tempAttribute );
                                                Ext.getCmp('filterAttributesPanel').update( me.mainForm.filter.attributes );
                                                me.addDataviewItemListeners();
                                                Ext.get('addAttrError').update('');
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    ]
                },
                {
                    xtype: 'panel',
                    border: false,
                    hidden: true,
                    id: 'addAttrpath',
                    items: [
                        {
                            xtype: 'component',
                            html: '<br>Interpolate attributes by mapping a file path. Note: This attribution will only apply to images matching the selected path. Also note that when attempting to match attributes within the specified categories, the software will automatically generate new attributes. For instance, if "Family" was specified within the path map, and a folder was named "Aceracae", but there is no attribute in "Family" named "Aceracae", then a new attribute will be created under "Family" with the title "Aceracae".<br>'
                        },
                        {
                            xtype: 'combo',
                            id: 'selectedpath',
                            width: 500,
                            fieldLabel: 'Select a path',
                            queryMode: 'local',
                            displayField: 'path',
                            valueField: 'path',
                            store: Ext.create('Ext.data.Store', {
                                fields: ['path'],
                                data: me.mainForm.filter.monitors
                            }),
                            listeners: {
                                change: function( combo, newVal, oldVal, opts ) {
                                    Ext.getCmp('pathnamecontainer').update( newVal );
                                    Ext.getCmp('pathboxlength').show();
                                }
                            }
                        },
                        {
                            xtype: 'combo',
                            id: 'pathboxlength',
                            hidden: true,
                            width: 500,
                            fieldLabel: 'Subfolders to map',
                            queryMode: 'local',
                            displayField: 'key',
                            valueField: 'value',
                            store: Ext.create('Ext.data.Store', {
                                fields: ['key','value'],
                                data: [
                                    { key: '1', value: 1 },
                                    { key: '2', value: 2 },
                                    { key: '3', value: 3 },
                                    { key: '4', value: 4 },
                                    { key: '5', value: 5 }
                                ]
                            }),
                            listeners: {
                                change: function( combo, newVal, oldVal, opts ) {
                                    var newComponents = [];
                                    for ( var i = 0; i < newVal; i++ ) {
                                        if ( i > 0 ) newComponents.push( Ext.create('Ext.form.Label', { text: '/' }) );
                                        newComponents.push( Ext.create('BISC.view.CustomPathAttribute', { id: 'pathattr' + i }) );
                                    }
                                    Ext.getCmp('pathbox').removeAll();
                                    Ext.getCmp('pathbox').add( newComponents );
                                }
                            }
                        },
                        {
                            xtype: 'component',
                            id: 'pathnamecontainer'
                        },
                        {
                            xtype: 'panel',
                            id: 'pathbox',
                            border: false,
                            layout: 'hbox'
                        },
                        {
                            xtype: 'component',
                            html: '/image.ext'
                        },
                        {
                            xtype: 'button',
                            scope: me,
                            handler: me.addCustomPath,
                            text: 'Add path attribution'
                        }
                    ]
                },
                {
                    xtype: 'panel',
                    border: false,
                    hidden: true,
                    id: 'addAttrfilename',
                    items: [
                        {
                            xtype: 'component',
                            html: '<br>Use regex.<br>'
                        },
                        {
                            xtype: 'textfield',
                            id: 'filenameRegex'
                        },
                        {
                            xtype: 'combo',
                            id: 'formatFilenameCombo',
                            queryMode: 'local',
                            displayField: 'value',
                            valueField: 'key',
                            store: Ext.create('Ext.data.Store', {
                                fields: ['key', 'value'],
                                data: [
                                    {key: 'upper', value: 'All Uppercase'},
                                    {key: 'lower', value: 'All Lowercase'},
                                    {key: 'ucfirst', value: 'First Character Uppercase'}
                                ]
                            }),
                            listeners: {
                                change: function( combo, newVal, oldVal, opts ) {
                                }
                            }
                        },
                        Ext.create('BISC.view.CustomPathAttribute', { id: 'filenameCat' }),
                        {
                            xtype: 'button',
                            scope: me,
                            handler: me.addCustomFilename,
                            text: 'Add filename attribution'
                        }
                    ]
                }
            ]
        });
        
        me.callParent(arguments);
    },
    addCustomPath: function() {
        var me = this;
        var tempAttribute = {
            id: me.mainForm.filter.tempId++,
            type: 'pathinterpolation',
            isAdd: true,
            isOverride: false,
            attributeId: '',
            category: {
                categoryId: '',
                title: '',
                bisId: ''
            },
            value: Ext.getCmp('selectedpath').getValue(),
            fields: []
        };
        var pathLength = Ext.getCmp('pathboxlength').getValue();
        var pathComponents = [];
        var flag = true;
        if ( pathLength != '' && pathLength != null ) {
            for ( var i = 0; i < pathLength; i++ ) {
                var val = Ext.getCmp('pathattr' + i).getValue();
                var categoryRecord = Ext.getCmp('pathattr' + i).findRecordByValue( val );
                if ( val == '' || val == null ) {
                    flag = false;
                    Ext.get('addAttrError').update('Please choose a category for each path segment.');
                } else {
                    tempAttribute.fields.push({
                        text: '{' + val + '}',
                        title: val,
                        id: categoryRecord.get('categoryId'),
                        bisId: categoryRecord.get('bisId')
                    });
                }
            }
            if ( flag ) {
                me.mainForm.filter.attributes.push( tempAttribute );
                Ext.getCmp('filterAttributesPanel').update( me.mainForm.filter.attributes );
                me.addDataviewItemListeners();
                Ext.get('addAttrError').update('');
            }
        }
    },
    addCustomFilename: function() {
        var me = this;
        var flag = true;
        var tempAttribute = {
            id: me.mainForm.filter.tempId++,
            type: 'filenameinterpolation',
            isAdd: true,
            isOverride: false,
            attributeId: '',
            category: {
                categoryId: '',
                title: '',
                bisId: ''
            },
            value: Ext.getCmp('filenameRegex').getValue(),
            format: Ext.getCmp('formatFilenameCombo').getValue(),
            fields: []
        };
        var val = Ext.getCmp('filenameCat').getValue();
        var categoryRecord = Ext.getCmp('filenameCat').findRecordByValue( val );
        if ( val == '' || val == null ) {
            flag = false;
            Ext.get('addAttrError').update('Please choose a category for the matched filename.');
        } else {
            tempAttribute.fields.push({
                text: '{' + val + '}',
                title: val,
                id: categoryRecord.get('categoryId'),
                bisId: categoryRecord.get('bisId')
            });
        }
        if ( flag ) {
            me.mainForm.filter.attributes.push( tempAttribute );
            Ext.getCmp('filterAttributesPanel').update( me.mainForm.filter.attributes );
            me.addDataviewItemListeners();
            Ext.get('addAttrError').update('');
        }
    },
    addDataviewItemListeners: function() {
        Ext.getCmp('filterAttributesPanel').getEl().select('.removeAttributeBtn').each( function( el ) {
            el.on( 'click', function( e, el, opts ) {
                var attributeId = el.getAttribute( 'attribute-id' );
                var attributes = Ext.getCmp('createFilterPanel').filter.attributes;
                Ext.each( attributes, function( attribute ) {
                    if ( attribute.id == attributeId ) {
                        attributes.splice( attributes.indexOf( attribute ), 1 );
                        Ext.getCmp('filterAttributesPanel').update( attributes );
                        Ext.getCmp('formAddFilterAttribute').addDataviewItemListeners();
                        return;
                    }
                });
            });
        });
        Ext.getCmp('filterAttributesPanel').getEl().select('.toggleAdditiveBtn').each( function( el ) {
            el.on( 'click', function( e, el, opts ) {
                var attributeId = el.getAttribute( 'attribute-id' );
                var attributes = Ext.getCmp('createFilterPanel').filter.attributes;
                Ext.each( attributes, function( attribute ) {
                    if ( attribute.id == attributeId ) {
                        attribute.isAdd = !attribute.isAdd;
                        Ext.getCmp('filterAttributesPanel').update( attributes );
                        Ext.getCmp('formAddFilterAttribute').addDataviewItemListeners();
                        return;
                    }
                });
            });
        });
        Ext.getCmp('filterAttributesPanel').getEl().select('.overrideCbx').each( function( el ) {
            el.on( 'click', function( e, el, opts ) {
                var attributeId = el.getAttribute( 'attribute-id' );
                var attributes = Ext.getCmp('createFilterPanel').filter.attributes;
                Ext.each( attributes, function( attribute ) {
                    if ( attribute.id == attributeId ) {
                        attribute.isOverride = !attribute.isOverride;
                        return;
                    }
                });
            });
        });
    },
    attributeExists: function( newAttribute ) {
        var flag = false;
        Ext.each( this.mainForm.filter.attributes, function( attribute ) {
            if ( attribute.attributeId == newAttribute.attributeId ) flag = true;
        });
        return flag;
    }
});
